package logic

import (
	"errors"
	"iot-base/auth/config"
	"iot-base/auth/db"
	"iot-base/auth/model"
	"iot-base/auth/svc"
	types2 "iot-base/auth/types"
	"iot-base/auth/utils"
	"strconv"
	"strings"
	"time"
)

type CompanyLogic struct {
}

func NewCompanyLogic() *CompanyLogic {
	return &CompanyLogic{}
}

func (l *CompanyLogic) Add(req types2.ReqAddCompany) (model.Company, error) {
	var company model.Company
	num, err := svc.Dao.TUser.FindCount(req.UserName)
	if err != nil {
		return company, err
	}
	if num >= 1 {
		return company, errors.New("用户名已存在。")
	}
	// todo 开启事务
	tx := db.Db.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()
	dataTime := time.Now()
	// 添加默认组
	var group model.AuthGroup
	group.ID = utils.GetUid()
	group.Pid = 1
	group.GroupName = req.Name
	group.CreatedAt = dataTime
	group.UpdatedAt = dataTime

	if group.Pid != 0 {
		// 查询上级的path
		pGroup, err := svc.Dao.TAuthGroup.GetGroupsByid(group.Pid)
		if err != nil {
			tx.Rollback()
			return company, err
		}
		group.Path = strings.Trim(pGroup.Path+"/"+strconv.FormatInt(group.Pid, 10), "/")
	}
	if err = tx.Create(&group).Error; err != nil {
		tx.Rollback()
		return company, err
	}

	// 添加用户信息
	salt := utils.GetRandomString(6)
	userInfo := model.User{
		UserName: req.UserName,
		NickName: req.UserName,
		UserType: config.CompanyAdmin,
		Salt:     salt,
		PassWord: utils.GetMd5Pwd(req.PassWord, salt),
	}
	userInfo.ID = utils.GetUid()
	userInfo.CreatedAt = dataTime
	userInfo.UpdatedAt = dataTime
	// 公司信息.
	company.Name = req.Name
	company.Remarks = req.Remarks
	company.IconImg = req.IconImg
	company.GroupId = group.ID
	if err = tx.Create(&company).Error; err != nil {
		tx.Rollback()
		return company, err
	}
	userInfo.CompanyId = company.ID
	if err = tx.Create(&userInfo).Error; err != nil {
		tx.Rollback()
		return company, err
	}
	userGroup := model.UserGroup{
		Uid:     userInfo.ID,
		GroupId: group.ID,
		RoleId:  req.RoleId,
	}
	if err = tx.Create(&userGroup).Error; err != nil {
		tx.Rollback()
		return company, err
	}
	tx.Commit()
	return company, nil
}

func (l *CompanyLogic) FindCount() (int64, error) {
	return svc.Dao.TCompany.FindCount()
}

func (l *CompanyLogic) FindList(page, size int) ([]model.Company, error) {
	return svc.Dao.TCompany.FindList(page, size)
}

func (l *CompanyLogic) Del(id int64) (int64, error) {
	return svc.Dao.TCompany.Del(id)
}

func (l *CompanyLogic) Update(data types2.ReqUpdateCompany) (int64, error) {
	var updateData model.Company
	updateData.IconImg = data.IconImg
	updateData.Remarks = data.Remarks
	updateData.Name = data.Name
	return svc.Dao.TCompany.Update(data.ID, &updateData)
}
